﻿axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

template.defaults.imports.dateFormat = function (date, format) {
    if (typeof (date) == "undefined" || date == null || date == "") return "";
    if (typeof (format) == "undefined") format = 'YYYY-MM-DD HH:mm:ss';
    return dayjs(date).format(format);
};

function closeWindow() {
    if (isRunWeiXin) {
        WeixinJSBridge.call('closeWindow');
    } else {
        window.close();
    }
}

function debug(obj) {
    var str = JSON.stringify(obj);
    showAlert2(str);
}

function parseErrorHtml(data, defaultMsg) {
    var myregexp = /<div class="mui-card-content-inner">\s*[\r\n]\s*(.*?)[\r\n]\s*<\/div>/;
    var match = myregexp.exec(data);
    var result = defaultMsg;
    if (match != null) {
        result = match[1];
    }
    return result;
}

function getTpl(url, cb) {
    axios.get(url).then(cb);
}


function previewReport(num, code, key, type) {
    if (typeof (type) == "undefined") type = "";
    showLoading('正在加载报告');
    axios.get("/Report/GetReportPreviewList", {
        params: {
            num: num,
            code: code,
            key: key,
            type: type
        }
    }).then(function (r) {
        var data = r.data;
        if (data.code == 0) {
            toast('获取报告成功');
            var cacheKey = data.cacheKey;
            mui.openWindow({
                id: 'reportPreview',
                url: "/Report/Preview?num=" + num + "&code=" + code + "&key=" + key + "&type=" + type + "&cacheKey=" + cacheKey
            })
        } else {
            showAlert(data.msg);
        }
    });
}

function toast(content) {
    layer.open({
        content: content,
        skin: 'msg',
        time: 2 //2秒后自动关闭
    });
}

function confirm(content, btn, cb) {
    layer.open({
        content: content,
        btn: btn,
        anim: 'up',
        skin: 'footer',
        yes: function (index) {
            layer.close(index);
            if (typeof (cb) == "function") {
                cb();
            }
        }
    });
}

function confirm2(content, btn, cb) {
    layer.open({
        content: content,
        btn: btn,
        anim: 'up',
        yes: function (index) {
            layer.close(index);
            if (typeof (cb) == "function") {
                cb();
            }
        }
    });
}

function showAlert(content) {
    layer.open({
        content: content,
        btn: '好的',
        shadeClose: false
    });
}

function showAlert2(content, cb) {
    layer.open({
        content: content,
        btn: '好的',
        shadeClose: false,
        yes: cb
    });
}

var loadingLayer = null;

function showLoading(content) {
    var id = "#layui-m-layer0  .layui-m-layermain  .layui-m-layercont p";
    if (loadingLayer != null && $(id).length > 0) { //如果加载提示正在显示 
        $(id).text(content);
        return;
    }
    var p = {
        type: 2,
        shadeClose: false,
    };
    if (typeof (content) != "undefined" && content.length > 0) {
        p.content = content;
    } else {
        p.content = "加载中...";
    }
    loadingLayer = layer.open(p);
}

function closeLoading() {
    if (loadingLayer != null) {
        layer.close(loadingLayer);
        loadingLayer = null;
    }
}
var modalLayer = null;

function showModal(html) {
    modalLayer = layer.open({
        type: 1,
        content: html,
        anim: 'down',
        style: 'position:fixed;maring:0;padding:0; left:0; top:0; width:100%; overflow: auto;height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
    });
    return modalLayer;
}

function closeModel() {
    if (modalLayer != null) {
        layer.close(modalLayer);
        modalLayer = null;
    }
}

function callApi(url, parm, complete, success, fail) {
    $.post(url, parm, function (r) {
        var data = r;
        if (typeof (complete) == "function")
            complete(r);
        if (data.code == 0) {
            if (typeof (success) == "function")
                success();
        } else {
            if (typeof (fail) == "function")
                fail(data.msg);
        }
    });
}

function waterfall(parm, parms, fun, complete) {
    var funs = [];
    for (var i = 0; i < parms.length; i++) {
        if (i == 0) {
            funs.push(async.apply(fun, parm, i, parms));
        } else {
            funs.push(fun);
        }
    }
    async.waterfall(funs, complete);
}

var advSearchDiv = null; 
function showAdvSearch() {
    var html = $('#advancedSearch').html();
    var index = showModal(html);
    var layerDivId = "layui-m-layer" + index;
    advSearchDiv = $('#' + layerDivId);
    initAdvSearchControl(advSearchDiv);
    initAdvSearchWhere(advSearchDiv, currentAdvWhere);
    if (typeof (customInitAdvSearchWhere) == "function") {
        customInitAdvSearchWhere(advSearchDiv, currentAdvWhere);
    } 
}

function initAdvSearchControl(whereDiv) {
    var inputs = whereDiv.find('input');
    inputs.each(function () {
        var input = $(this);
        if (input[0].type == 'date') {
            input.on('change', function () {
                this.className = (this.value != '' ? 'has-value' : '')
            });
        }
    });
}

function initAdvSearchWhere(div, whereData) {
    if (typeof (whereData) != undefined) {
        for (var p in whereData) {
            var input = div.find('#query_' + p);
            if (input.length > 0) {
                input.val(whereData[p]);
                if (input[0].type == 'date') {
                    input.trigger('change');
                }
            }
        }
    }
}

function clearAdvSearchWhere() {
    if (typeof (customClearAdvSearchWhere) == "function") {
        customClearAdvSearchWhere(advSearchDiv);
    } else {
        var inputs = advSearchDiv.find('input');
        inputs.each(function () {
            var input = $(this);
            input.val('');
            if (input[0].type == 'date') {
                input.trigger('change');
            }
        });
    }
}

function closeAdvSearch() {
    advSearchDiv = null;
    closeModel();
}

var currentAdvWhere = {};

function advSearch() {
    if (typeof (getAdvSearchWhereData) == "function") {
        currentAdvWhere = getAdvSearchWhereData(advSearchDiv); //自定义查询条件获取方法
    } else {
        var inputs = advSearchDiv.find('input');
        inputs.each(function () {
            var input = $(this);
            var id = input.attr('id');
            var p = id.substr(6); //必须以 query_ 开头，示例：query_startDate
            var v = input.val();
            currentAdvWhere[p] = v;
        });
    }
    if (typeof (queryAdvSearchData) == "function") {
        queryAdvSearchData(currentAdvWhere);
    } else {
        if(typeof(search) == "function") {
            search(true);
        }
    }
    closeAdvSearch();
}

function bindAdvSearchEvent() {
    if ($('#btnShowAdvSearch').length > 0) {
        $('#btnShowAdvSearch').on('tap', function () {
            showAdvSearch();
        });
    }
}

mui.ready(function () {
    bindAdvSearchEvent();
    mui('.mui-scroll-wrapper').scroll();
    mui('#list').on('tap', 'a', function () {
        mui.openWindow({
            url: this.href
        })
    });
});